<?php
require_once dirname(__FILE__)."/base_model.php";
/**
 * 事件类
 * @author xucongbin
 * @since
 */
class Events extends base_model {

	const EVENT_TABLE = 'table_event';
	const EVENT_ATTACHMENT_TABLE = 'table_attachment';
	const EVENT_WORK_RECORD_TABLE = 'table_workrecord';
	const EVENT_INCREMENT_DEPTH = 1;
	//事件类型
    const EVENT_TYPE_SERVICE_REQUEST = 2;
	const EVENT_TYPE_FAULT_REPORT = 1;
	const EVENT_TYPE_INFO_REQUEST = 4;
	const EVENT_TYPE_COMPLAINT = 3;
	const EVENT_TYPE_INFO_REQUEST_NOTECH = 5;
    /*protected static $eventTypes = array(
        self::EVENT_TYPE_SERVICE_REQUEST=>'服务请求',
        self::EVENT_TYPE_FAULT_REPORT=>'故障报告',
        self::EVENT_TYPE_INFO_REQUEST=>'信息咨询（技术类）',
        self::EVENT_TYPE_COMPLAINT=>'投诉',
        self::EVENT_TYPE_INFO_REQUEST_NOTECH=>'信息咨询（非技术类）'
    );*/
    //事件状态
	/**
    const EVENT_STATUS_CREATE = 25;
	const EVENT_STATUS_PROCESSING = 26;
	const EVENT_STATUS_SOLUTION = 27;
	const EVENT_STATUS_CLOSE = 28;
	/**
	static EVENT_STATUS_CREATE		= events_config::$event_status['EVENT_STATUS_CREATE'];
	static EVENT_STATUS_PROCESSING	= events_config::$event_status['EVENT_STATUS_PROCESSING'];
	static EVENT_STATUS_SOLUTION	= events_config::$event_status['EVENT_STATUS_SOLUTION'];
	static EVENT_STATUS_CLOSE		= events_config::$event_status['EVENT_STATUS_CLOSE'];
    /*protected static $eventStatus = array(
        self::EVENT_STATUS_CREATE=>'新建',
        self::EVENT_STATUS_PROCESSING=>'处理中',
        self::EVENT_STATUS_SOLUTION=>'解决',
        self::EVENT_STATUS_CLOSE=>'关闭'
    );*/

    //事件优先级
    const EVENT_PRIORITY_NULL = 1;
	const EVENT_PRIORITY_LOWEST = 2;
	const EVENT_PRIORITY_MIDDLE = 3;
	const EVENT_PRIORITY_HIGH = 4;
	const EVENT_PRIORITY_EMERGENCY = 5;
    protected static $eventPriority = array(
//        self::EVENT_PRIORITY_NULL=>'无',
        self::EVENT_PRIORITY_LOWEST=>'低',
        self::EVENT_PRIORITY_MIDDLE=>'中',
        self::EVENT_PRIORITY_HIGH=>'高',
        self::EVENT_PRIORITY_EMERGENCY=>'紧急'
    );
    //事件紧急程度
	const EVENT_EMERGENCY_LOWEST = 1;
	const EVENT_EMERGENCY_MIDDLE = 2;
	const EVENT_EMERGENCY_HIGH = 3;
	const EVENT_EMERGENCY_HIGHEST = 4;
    protected static $eventEmergency = array(
        self::EVENT_EMERGENCY_LOWEST=>'低',
        self::EVENT_EMERGENCY_MIDDLE=>'中',
        self::EVENT_PRIORITY_HIGH=>'高',
        self::EVENT_EMERGENCY_HIGHEST=>'紧急'
    );

    //影响范围
    const EVENT_INFLUENCEAREA_NULL = 9;
	const EVENT_INFLUENCEAREA_FEW_USERS = 8;
	const EVENT_INFLUENCEAREA_SECONDARY = 7;
	const EVENT_INFLUENCEAREA_MAIN = 6;
    /*protected static $eventInfluencearea = array(
        self::EVENT_INFLUENCEAREA_NULL=>'无业务无影响',
        self::EVENT_INFLUENCEAREA_FEW_USERS=>'影响个别用户',
        self::EVENT_INFLUENCEAREA_SECONDARY=>'影响次要业务',
        self::EVENT_INFLUENCEAREA_MAIN=>'影响主要业务'
    );*/

    //事件来源
    const EVENT_SOURCE_CUSTOMER_MAIL = 18;
	const EVENT_SOURCE_ACCOUNT_SD = 19;
	const EVENT_SOURCE_CUSTOMER_TELPHONE = 20;
	const EVENT_SOURCE_MAINTENANCE = 21;
	const EVENT_SOURCE_INFO_NOTICE = 22;
	const EVENT_SOURCE_SERVICE_NOTICE = 23;
	const EVENT_SOURCE_OTHER = 24;
    /*protected static $eventSources = array(
        self::EVENT_SOURCE_CUSTOMER_MAIL=>'客户邮件报告',
        self::EVENT_SOURCE_ACCOUNT_SD=>'大客户部报告',
        self::EVENT_SOURCE_CUSTOMER_TELPHONE=>'客户电话报告',
        self::EVENT_SOURCE_MAINTENANCE=>'运维发现',
        self::EVENT_SOURCE_INFO_NOTICE=>'信息化通知',
        self::EVENT_SOURCE_SERVICE_NOTICE=>'第三方服务通知',
        self::EVENT_SOURCE_OTHER=>'其它'
    );*/

    //用户类型
    const USER_TYPE_SNDA_COMPANY = 14;
	const USER_TYPE_SDO_USER = 15;
	const USER_TYPE_EXTENAL_COMPANY = 16;
	const USER_TYPE_EXTENAL_PERSON = 17;
    /*protected static $eventUserTypes = array(
        self::USER_TYPE_SNDA_COMPANY=>'集团子公司用户',
        self::USER_TYPE_SDO_USER=>'SDO内部用户',
        self::USER_TYPE_EXTENAL_COMPANY=>'外部企业用户',
        self::USER_TYPE_EXTENAL_PERSON=>'外部个人用户'
    );*/
	//用以区别是内部用户提交还是外部商户提交， 1为内部商户，2外部
	const USER_STAFF_INNER = 1;
	const USER_STAFF_OUTER = 2;

	const ATTACHMENT_ISREPLY = 1;
	const ATTACHMENT_NOTREPLY = 2;

	protected $errCode = array(
	    -1=>'the event not exists',
	    -2=>'the event status not exists.',
	    -3=>'the event priority not exists.',
	    -4=>'the attach not exists.',
	    -5=>'the workrecord not exists.',
	    -6=>'the charger not belong in workers.'

	);
    protected $options;
    protected $workers;
	public function __construct() {
		parent::__construct();
		$this->load->model('options');
		$this->load->model('workers');
	}
    /**
     * 创建事件
     * @param string $title 标题
     * @param string $desc 描述
     * @param string $pt 创建者
     * @param int $catId 类别
     * @param int $type 类型
     * @param array $row array(
     *  event_usertype=>用户类型,
     * 	event_stauts=>事件状态,
     *  event_emergency	=>	紧急程度
     *  event_influencearea	=>	影响范围
     *  event_subclass	=>	子类
     *  event_solution => 解决方案
     *  event_source => 事件来源
     *  event_influencebusiness	=>影响业务
     *  event_addtime =>0000-00-00 00:00:00	提交时间
     *  event_deadline	=>	0000-00-00 00:00:00	事件逾期时间
     * )
     * @return boolean|int成功返回evnet_id,失败返回false
     */
	public function createEvent($title, $desc, $pt, $catId, $type, $row=array())
	{
	    $row = array_merge($row, array(
	        'event_title'=>$title,
	        'event_desc'=>$desc,
	        'event_owner'=>$pt,
	        'event_category'=>$catId,
	        'event_type'=>$type
	    ));

	    if (!isset($row['event_addtime'])) {
	    	$row['event_addtime'] = date("Y-m-d H:i:s");
	    }
	    $row['event_updatetime'] = date("Y-m-d H:i:s");
	    if (!isset($row['event_status'])) {
	    	$row['event_status'] = events_config::$event_status['EVENT_STATUS_CREATE'];
	    }
	    if (!isset($row['event_emergency'])) {
	    	$row['event_emergency'] = self::EVENT_PRIORITY_NULL;
	    }
	    if (!isset($row['event_influencearea'])) {
	    	$row['event_influencearea'] = self::EVENT_INFLUENCEAREA_FEW_USERS;
	    }
	    if (!isset($row['event_subclass'])) {
	    	$row['event_subclass'] = 0;
	    }
	    if (!$this->db->insert(self::EVENT_TABLE, $row)) {
	        $this->logger->err("add event failure,title-{$title}, pt-{$pt}, catId-{$catId}, type-{$type}.");
	        return false;
	    }
	    return $this->db->insert_id();
	}
	/**
	 * 更新事件内容
	 * @param int $eventId 事件号
	 * @param array $row
	 * @return boolean
	 */
    public function modifyEventById($eventId, $row=array())
	{
	    $tmp = $this->getEventById($eventId);
	    if(!$tmp) {
	        $this->_setError(-1, "the event({$eventId}) not exists.");
	        return false;
	    }
	    $row['event_updatetime'] = date("Y-m-d H:i:s");
	    if (!$this->db->update(self::EVENT_TABLE, $row, array('event_id'=>$eventId))) {
	    	$this->logger->err("update event failure,event_id:{$eventId}.");
	        return false;
	    }
	    return true;
	}
	/**
	 * 追加描述
	 * @param int $eventId 事件号
	 * @param array $row
	 * @return boolean
	 */
    public function appendDescById($eventId, $row=array())
	{
	    $tmp = $this->getEventById($eventId);
	    if(!$tmp) {
	        $this->_setError(-1, "the event({$eventId}) not exists.");
	        return false;
	    }
	    $row['event_updatetime'] = date("Y-m-d H:i:s");
	    $row['event_desc'] = $tmp['event_desc'].$row['event_desc'];
	    if (!$this->db->update(self::EVENT_TABLE, $row, array('event_id'=>$eventId))) {
	    	$this->logger->err("update event failure,event_id:{$eventId}.");
	        return false;
	    }
	    return true;
	}
	/**
	 * 删除事件
	 * @param int $eventId
	 * @return boolean
	 */
    public function deleteEventById($eventId)
	{
	    $tmp = $this->getEventById($eventId);
	    if(!$tmp) {
	        $this->_setError(-1, "the event({$eventId}) not exists.");
	        return false;
	    }
	    if (!$this->db->delete(self::EVENT_TABLE, array('event_id'=>$eventId))) {
	    	$this->logger->err("delete event failure,event_id:{$eventId}.");
	        return false;
	    }
	    return true;
	}
	/**
	 * 设置事件状态
	 * @param int $eventId 事件号
	 * @param int $status
	 * @return boolean
	 */
    public function setEventStatus($eventId, $status)
	{
	    if (!$this->getEventStatus($status)) {
	    	$this->_setError(-2, "the event status({$status}) not exists.");
	        return false;
	    }
	    if (!$this->modifyEventById($eventId, array('event_status'=>$status))) {
	    	$this->logger->err("set event status failure,event_id:{$eventId}, status:{$status}.");
	        return false;
	    }
	    return true;
	}
	/**
	 * 修改事件优先级
	 * @param int $eventId
	 * @param int $priority
	 * @return boolean
	 */
    public function setEventPriority($eventId, $priority)
	{
	    if (!isset(self::$eventPriority[$priority])) {
	    	$this->_setError(-3, "the event priority({$priority}) not exists.");
	        return false;
	    }
	    if (!$this->modifyEventById($eventId, array('event_emergency'=>$priority))) {
	    	$this->logger->err("set event priority failure,event_id:{$eventId}, priority:{$priority}.");
	        return false;
	    }
	    return true;
	}
	/**
	 * 获取事件内容
	 * @param int $eventId
	 * @param array $fields 字段
	 * @return array
	 */
	public function getEventById($eventId, $fields=null)
	{
	    $this->db->from(self::EVENT_TABLE);
	    $this->db->where('event_id', $eventId);
	    if ($fields) {
	    	$this->db->select($fields);
	    }
	    return $this->db->get()->row_array();
	}
	/**
	 * 获取事件列表
	 * @param array $where
	 * @param int $offset
	 * @param int $count
	 * @param string $sort
	 * @return array
	 */
	public function getEventList($where, $offset=0, $count=null, $orderby=null, $sort=null)
	{
	   $this->db->from(self::EVENT_TABLE);
	   foreach($where as $k=>$row) {
	       if (is_array($row)) {
	       	    $this->db->where_in($k, $row);
	       	    unset($where[$k]);
	       }
	   }
	   $this->db->where($where);
	   if ($count) {
	       $this->db->limit($count);
	   }
	   if ($offset) {
	       $this->db->offset($offset);
	   }
	   if ($orderby) {
	       if ($sort) {
	       	   $this->db->orderby($orderby, $sort);
	       } else {
	           $this->db->orderby($orderby);
	       }
	   }
	   return $this->db->get()->result_array();
	}
	/**
	 * 获取事件记录条数
	 * @param array $where
	 * @return int
	 */
    public function getEventCount($where)
	{
	   $this->db->from(self::EVENT_TABLE);

	   $this->db->select("count(*) as c");
	   foreach($where as $k=>$row) {
	       if (is_array($row)) {
	       	    $this->db->where_in($k, $row);
	       	    unset($where[$k]);
	       }
	   }
	   $this->db->where($where);
	   $row = $this->db->get()->row_array();
	   return intval($row['c']);
	}
	/**
	 * 获取事件状态
	 * @param int $code
	 * @return array|string
	 */
	public function getEventStatus($code=null)
	{
	    $result = $this->options->getTableOptions("event_status", $code);
	    if ($code) {
	    	return $result[0];
	    }
	    return $result;
	}
	/**
	 * 获取事件类型
	 * @param int $code
	 * @return string|array
	 */
    public function getEventType($code=null)
	{
	    $result = $this->options->getTableOptions("event_type", $code);
	    if ($code) {
	    	return $result[0];
	    }
	    return $result;
	}
	/**
	 * 获取事件重要程度
	 * @param int $code
	 * @return string|array
	 */
    public static function getEventEmergency($code=null)
	{
	    if (is_null($code)) {
	    	return self::$eventEmergency;
	    }
	    return self::$eventEmergency[$code];
	}
	/**
	 * 获取事件优先级
	 * @param int $code
	 * @return string|array
	 */
    public static function getEventPriority($code=null)
	{
	    if (is_null($code)) {
	    	return self::$eventPriority;
	    }
	    return self::$eventPriority[$code];
	}
	/**
	 * 获取事件影响范围
	 * @param int $code
	 * @return string|array
	 */
    public function getEventInfluencearea($code=null)
	{
	    $result = $this->options->getTableOptions("event_influencearea", $code);
	    if ($code) {
	    	return $result[0];
	    }
	    return $result;
	}
	/**
	 * 获取事件来源名称
	 * @param int $code
	 * @return string|array
	 */
    public function getEventSource($code=null)
	{
	    $result = $this->options->getTableOptions("event_source", $code);
	    if ($code) {
	    	return $result[0];
	    }
	    return $result;
	}
	public function setEventCharger($eventId, $newCharger)
	{
	    $tmp = $this->getEventById($eventId);
	    if(!$tmp) {
	        $this->_setError(-1, "the event({$eventId}) not exists.");
	        return false;
	    }
	    $tmp = $this->workers->getWorkerByName($newCharger);
	    if (!$tmp) {
	    	$this->_setError(-6, "the charger({$eventId}) not belong in workers.");
	        return false;
	    }
	    $row = array(
	        'event_charger'=>$newCharger,
	        'event_groupid'=>$tmp['worker_groupid']
	    );
	    return $this->modifyEventById($eventId, $row);
	}
	/**
	 * 添加附件
	 * @param int $eventId
	 * @param string $pt
	 * @param string $path
	 * @param string $name
	 * @param array $row array(
	 * 	event_isreply => 1 提交事件关联的附件 2 后台处理事件上传的附件
	 * )
	 *
	 * @return int|boolean
	 */
	public function addAttachment($eventId, $pt, $path, $name, $row=array())
	{
	    $tmp = $this->getEventById($eventId);
	    if(!$tmp) {
	        $this->_setError(-1, "the event({$eventId}) not exists.");
	        return false;
	    }
	    $row = array_merge($row, array(
	        'event_id'=>$eventId,
	        'attachment_owner'=>$pt,
	        'attachment_path'=>$path,
	        'attachment_name'=>$name
	    ));
	    if (!$this->db->insert(self::EVENT_ATTACHMENT_TABLE, $row)) {
	    	$this->logger->err("add event attachment failure,event_id:{$eventId}, owner:{$pt}, name:{$name}.");
	        return false;
	    }
	    return $this->db->insert_id();
	}
	/**
	 * 更新附件内容
	 * @param int $attachId
	 * @param array $row
	 * @return boolean
	 */
	public function modifyAttachmentById($attachId, $row)
	{
	    $tmp = $this->getAttachmentById($attachId);
	    if(!$tmp) {
	        $this->_setError(-4, "the attach({$attachId}) not exists.");
	        return false;
	    }
	    if (!$this->db->update(self::EVENT_ATTACHMENT_TABLE, $row, array('attachment_id'=>$attachId))) {
	    	$this->logger->err("modify event attachment failure,attachment_id:{$attachId}.");
	        return false;
	    }
	    return true;
	}
	/**
	 * 删除附件，根据ID
	 * @param int $attachId
	 * @return bollean
	 */
	public function deleteAttachmentById($attachId)
	{
	    $tmp = $this->getAttachmentById($attachId);
	    if(!$tmp) {
	        $this->_setError(-4, "the attach({$attachId}) not exists.");
	        return false;
	    }
	    if (!$this->db->delete(self::EVENT_ATTACHMENT_TABLE, array('attachment_id'=>$attachId))) {
	    	$this->logger->err("delete event attachment failure,attachment_id:{$attachId}.");
	        return false;
	    }
	    return true;
	}
	/**
	 * 删除事件附件
	 * @param int $eventId
	 * @return boolean
	 */
    public function removeAttachmentByEvent($eventId)
	{
	    $tmp = $this->getEventById($eventId);
	    if(!$tmp) {
	        $this->_setError(-1, "the event({$eventId}) not exists.");
	        return false;
	    }
	    if (!$this->db->delete(self::EVENT_ATTACHMENT_TABLE, array('event_id'=>$eventId))) {
	    	$this->logger->err("delete attachment failure,event_id:{$eventId}.");
	        return false;
	    }
	    return true;
	}
	/**
	 * 获取事件附件列表
	 * @param int $eventId
	 * @return array
	 */
	public function getAttachmentByEventId($eventId)
	{
	    $this->db->from(self::EVENT_ATTACHMENT_TABLE);
	    $this->db->where('event_id', $eventId);
	    return $this->db->get()->result_array();
	}
	/**
	 * 获取附件内容，根据ID
	 * @param unknown_type $attachId
	 */
	public function getAttachmentById($attachId)
	{
	    $this->db->from(self::EVENT_ATTACHMENT_TABLE);
	    $this->db->where('attachment_id', $attachId);
	    return $this->db->get()->row_array();
	}

	/**
	 * 添加工作记录
	 * @param int $eventId 事件ID
	 * @param string $pt 人名（公司内部）
	 * @param string $content 工作说明
	 * @param string $date 创建日期,默认为当前日期
	 * @return int|boolean
	 */
	public function addWorkRecord($eventId, $pt, $content, $date=null)
	{
	    if (!$date)
	    {
	    	$date = date("Y-m-d H:i:s");
	    }
		$row			= $this->getEventById($eventId, 'event_records');
		$work_record	= $row['event_records']
						. $pt . " " . $date . $content
						. "\n---------------------------------------\n";
		return $this->modifyEventById($eventId, array('event_records'=>$work_record));
//	    $tmp = $this->getEventById($eventId);
//	    if(!$tmp) {
//	        $this->_setError(-1, "the event({$eventId}) not exists.");
//	        return false;
//	    }
//	    if (!$date) {
//	    	$date = date("Y-m-d H:i:s");
//	    }
//	    $row = array(
//	        'event_id'=>$eventId,
//	        'staff_name'=>$pt,
//	        'operate_content'=>$content,
//	        'operate_date'=>$date
//	    );
//	    if (!$this->db->insert(self::EVENT_WORK_RECORD_TABLE, $row)) {
//	    	$this->logger->err("add event workrecord failure,event_id:{$eventId}, owner:{$pt}.");
//	        return false;
//	    }
//	    return $this->db->insert_id();
	}
	/**
	 * 更新工作记录
	 * @param int $workId
	 * @param array $row array(
	 * 	staff_name  =>  人名（公司内部）
	 *  operate_date  =>0000-00-00 00:00:00 操作时间
	 *  operate_content => 工作说明
	 *  event_id  => 事件ID（关联）
	 * )
	 * @return boolean
	 */
	public function modifyWorkRecordById($workId, $row)
	{
	    $tmp = $this->getWorkRecordById($workId);
	    if(!$tmp) {
	        $this->_setError(-5, "the workrecord({$workId}) not exists.");
	        return false;
	    }
	    if (!$this->db->update(self::EVENT_WORK_RECORD_TABLE, $row, array('id'=>$workId))) {
	    	$this->logger->err("modify event workrecord failure,worker_id:{$workId}.");
	        return false;
	    }
	    return true;
	}
	/**
	 * 删除工作记录，根据ID
	 * @param int $workId
	 * @return bollean
	 */
	public function deleteWorkRecordById($workId)
	{
	    $tmp = $this->getWorkRecordById($workId);
	    if(!$tmp) {
	        $this->_setError(-5, "the workrecord({$workId}) not exists.");
	        return false;
	    }
	    if (!$this->db->delete(self::EVENT_WORK_RECORD_TABLE, array('id'=>$workId))) {
	    	$this->logger->err("delete event workrecord failure,worker_id:{$workId}.");
	        return false;
	    }
	    return true;
	}
	/**
	 * 删除工作记录,根据事件ID
	 * @param int $eventId
	 * @return boolean
	 */
    public function removeWorkRecordByEvent($eventId)
	{
	    $tmp = $this->getEventById($eventId);
	    if(!$tmp) {
	        $this->_setError(-1, "the event({$eventId}) not exists.");
	        return false;
	    }
	    if (!$this->db->delete(self::EVENT_WORK_RECORD_TABLE, array('event_id'=>$eventId))) {
	    	$this->logger->err("delete workrecord failure,event_id:{$eventId}.");
	        return false;
	    }
	    return true;
	}
	/**
	 * 获取事件工作记录列表
	 * @param int $eventId
	 * @return array
	 */
	public function getWorkRecordByEventId($eventId)
	{
	    $this->db->from(self::EVENT_WORK_RECORD_TABLE);
	    $this->db->where('event_id', $eventId);
	    return $this->db->get()->result_array();
	}
	/**
	 * 获取工作记录内容，根据ID
	 * @param int $workId
	 * @return array
	 */
	public function getWorkRecordById($workId)
	{
	    $this->db->from(self::EVENT_WORK_RECORD_TABLE);
	    $this->db->where('id', $workId);
	    return $this->db->get()->row_array();
	}

	public function generateEventId()
	{
	    $this->db->from(self::EVENT_TABLE);
	    $this->db->select('MAX(event_id) as max_id');
	    $row = $this->db->get()->row_array();
	    return intval($row['max_id'])+self::EVENT_INCREMENT_DEPTH;
	}
}